//
//  PostCommentViewController.m
//  OrderSeat
//
//  Created by wangwei on 13-10-9.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "PostCommentViewController.h"

#define INPUT_MARK @"请输入您的评论信息"

@interface PostCommentViewController ()

@property (strong, nonatomic) NSMutableDictionary *selectedTitles;
@property (strong, nonatomic) NSMutableArray *buttonTitles;
@property (strong, nonatomic) NSMutableDictionary *titlesForButton;
@property (strong, nonatomic) UIColor *oldColor;

@end

@implementation PostCommentViewController

- (id)initWithShopId:(NSString*)shopId
{
    self = [super initWithNibClass:[PostCommentViewController class]];
    if (self) {
        self.shopId = shopId;
        _dataSource = [[PostCommentDataSource alloc] initWithVC:self];
        _buttonTitles = [[NSMutableArray alloc] initWithCapacity:9];
        _selectedTitles = [NSMutableDictionary dictionaryWithCapacity:9];
        _titlesForButton = [[NSMutableDictionary alloc] initWithCapacity:3];
        [self initButtonTitles];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"我的点评"];
    
    _oldColor = _txtComments.textColor;
    
    [self.view addTarget:self action:@selector(viewTapped:)];
    [self reLayoutSubviews];
}

- (void)leftButtonClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
}

-(void)viewTapped:(id)sender
{
    if ([self.txtPrice resignFirstResponder] || [self.txtComments resignFirstResponder]) {
        if ([_txtComments.text isEqualToString:@""]) {
            _txtComments.text = INPUT_MARK;
            _txtComments.textColor = _oldColor;
        }
        
        [self.theScrollview setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.theScrollview setContentOffset:CGPointMake(0, 150) animated:YES];
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([_txtComments.text isEqualToString:INPUT_MARK]) {
        _txtComments.text = @"";
        _txtComments.textColor = [UIColor blackColor];
    }
    
    [self.theScrollview setContentOffset:CGPointMake(0, 200) animated:YES];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if ([_txtComments.text isEqualToString:@""]) {
        _txtComments.text = INPUT_MARK;
        _txtComments.textColor = _oldColor;
    }
}

- (IBAction)TextField_DidEndOnExit:(id)sender
{
    // 隐藏键盘.
    [sender resignFirstResponder];
    [self.theScrollview setContentOffset:CGPointMake(0, 0) animated:YES];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    else if([text length] == 0 && [textView.text length] > 0) {
        NSString *str = [textView.text substringToIndex:textView.text.length-1];
        [self indexButtonForText:str];
    }
    else {
        [self indexButtonForText:textView.text];
    }
    
    return YES;
}

- (IBAction)totalStarAction:(id)sender
{
    [self doStarForTag:1000 andSender:sender];
}

- (IBAction)serviceStarAction:(id)sender
{
    [self doStarForTag:2000 andSender:sender];
}

- (IBAction)tastStarAction:(id)sender
{
    [self doStarForTag:3000 andSender:sender];
}

- (IBAction)envStarAction:(id)sender
{
    [self doStarForTag:4000 andSender:sender];
}

- (void)doStarForTag:(int)tag andSender:(id)sender
{
    int startTag = tag + 1;
    int endTag = tag + 5;
    int btnTag = [sender tag];
    
    for (int i = startTag; i <= btnTag; i++) {
        UIButton *button = (UIButton*)[_headView viewWithTag:i];
        [button setSelected:YES];
    }
    for (int i = btnTag+1; i <= endTag; i++) {
        UIButton *button = (UIButton*)[_headView viewWithTag:i];
        [button setSelected:NO];
    }
    
    int star = btnTag-tag;
    UILabel *starLabel = (UILabel*)[_headView viewWithTag:endTag+1];
    starLabel.text = INT_TO_STR(star);
}

- (IBAction)commentAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    if (button.selected) return;
    
    _betterBtn.selected =
    _commonBtn.selected =
    _suggestBtn.selected = NO;
    [sender setSelected:YES];
    
    self.buttonTitles = [_titlesForButton objectForKey:INT_TO_STR([sender tag])];
    for (int i = 0; i < _buttonTitles.count; i++) {
        NSString *title = [_buttonTitles objectAtIndex:i];
        UIButton *button = (UIButton *)[_footerView viewWithTag:(1000+i)];
        [button setTitleForNormal:title];
    }
    
    [self clearSelected];
    [self indexButtonForText:_txtComments.text];
}

- (IBAction)selCommTitlesAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    if (_selectedTitles.count >= 6 && !button.selected) {
        [AppDelegate showMessage:@"不能选择超过6项评价"];
        return;
    }
    
    button.selected = !button.selected;
    if ([_txtComments.text isEqualToString:INPUT_MARK]) {
        _txtComments.text = @"";
        _txtComments.textColor = [UIColor blackColor];
    }
    
    NSString *title = [_buttonTitles objectAtIndex:(button.tag-1000)];
    NSString *sel_title = [NSString stringWithFormat:@"%@ ",title];

    if (button.selected) {
        [_selectedTitles setObject:title forKey:title];
        _txtComments.text = [_txtComments.text stringByAppendingString:sel_title];
    }
    else {
        [_selectedTitles removeObjectForKey:title];
        _txtComments.text = [_txtComments.text stringByReplacingOccurrencesOfString:sel_title withString:@""];
    }
    
    if ([_txtComments.text isEqualToString:@""]) {
        _txtComments.text = INPUT_MARK;
        _txtComments.textColor = _oldColor;
    }
}

- (void)clearSelected
{
    for (int i = 0; i < 9; i++) {
        UIButton *button = (UIButton *)[_footerView viewWithTag:(1000+i)];
        button.selected = NO;
    }
}

- (void)initButtonTitles
{
    NSArray *titles1 = @[@"味道不错",@"性价比高",@"环境雅致",@"强烈推荐",@"服务很好",@"停车方便",@"装修豪华",@"卫生干净",@"值得再来"];
    
    NSArray *titles2 = @[@"味道一般",@"性价适中",@"服务还行",@"环境一般",@"车位紧张",@"不及想象",@"没有折扣",@"卫生一般",@"上菜较慢"];
    
    NSArray *titles3 = @[@"请优化环境",@"请加强卫生",@"请改善服务",@"请提升口味",@"请加快速度",@"请加大菜量",@"请免费无线",@"请网上点菜",@"请降低价格"];
    
    [_titlesForButton setObject:titles1 forKey:@"5001"];
    [_titlesForButton setObject:titles2 forKey:@"5002"];
    [_titlesForButton setObject:titles3 forKey:@"5003"];
    
    _buttonTitles = [_titlesForButton objectForKey:@"5001"];
}

- (void)indexButtonForText:(NSString *)text
{
    int tag = _betterBtn.selected ? 5001 : (_commonBtn.selected ? 5002 : 5003);
    NSArray *buttons = [_titlesForButton objectForKey:INT_TO_STR(tag)];
    for (NSString *title in [_selectedTitles allKeys]) {
        int index = 0;
        for (NSString *n_title in buttons) {
            if ([title isEqualToString:n_title]) {
                UIButton *button = (UIButton *)[_footerView viewWithTag:index+1000];
                button.selected = YES;
            }
            index++;
        }
    }
}

- (IBAction)postAction:(id)sender
{
    if (![self checkForm])return;
    
    NSString *total = ((UILabel *)[_headView viewWithTag:1006]).text;
    NSString *service = ((UILabel *)[_headView viewWithTag:2006]).text;
    NSString *tast = ((UILabel *)[_headView viewWithTag:3006]).text;
    NSString *envr = ((UILabel *)[_headView viewWithTag:4006]).text;
    
    NSString *url = [NSString stringWithFormat:API_SHOP_COMPOST,_shopId,[AppSetting userName],tast, envr, service, total, _txtPrice.text, _txtComments.text];
    
    [_dataSource postCommentsWithURL:url];
    [SVProgressHUD showWithStatus:@"正在提交您的点评..."];
}

- (BOOL)checkForm
{
    if ([_txtPrice.text isEqualToString:@""]) {
        [AppDelegate showMessage:@"请填写人均消费价格！"];
        return NO;
    }
    if ([_txtComments.text isEqualToString:INPUT_MARK]) {
        [AppDelegate showMessage:@"请填写点评内容！"];
        return NO;
    }
    if (!_betterBtn.selected && !_commonBtn.selected && !_suggestBtn.selected) {
        [AppDelegate showMessage:@"请选择 [好评]、[一般]、[建议] 进行点评！"];
        return NO;
    }
    
    return YES;
}

- (void)reLayoutSubviews
{
    _theScrollview.height = ScreenHeight == iPhone4_Height ? iPhone4_ViewHeight : iPhone5_ViewHeight;
    
    [UIView drawBorders:@[_headView, _bodyView1, _bodyView2, _footerView]];
    [UIView autoLayoutVertical:@[_headView, _bodyView1, _bodyView2, _footerView, _submitBtn]];
    [_theScrollview autoHeight];
}

@end

//==========================================================================================
#pragma ===================数据源类实现=======================================================
//==========================================================================================

@implementation PostCommentDataSource

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
    }
    return self;
}

- (void)postCommentsWithURL:(NSString *)url
{
    [self get:url];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@", request.responseString);
    
    NSDictionary *json = [request.responseData JSONValue];
    if ([[json objectForKey:@"error_code"] intValue] != 0) {
        return;
    }
    
    NSDictionary *data = [json objectForKey:@"data"];
    if ([[data objectForKey:@"state"] intValue] == 1) {
        [SVProgressHUD dismissWithSuccess:@"点评成功！"];
        [_viewController performSelector:@selector(leftButtonClick:) withObject:nil afterDelay:1];
    }
    else if([[data objectForKey:@"state"] intValue] == 2) {
        [SVProgressHUD dismissWithError:@"登录状态或会员不存在！"];
    }
    else {
        [SVProgressHUD dismissWithError:@"您的点评提交失败！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    [super requestFailed:request];
}


@end




